package com.boya.demo.controlloer;


import com.boya.demo.dao.DicDao;
import com.boya.demo.dao.OrdersDao;
import com.boya.demo.dao.PriceDao;
import com.boya.demo.entity.Dic;
import com.boya.demo.entity.Orders;
import com.boya.demo.entity.Price;
import com.boya.demo.utils.DateUtils;
import com.boya.demo.utils.ExcelUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;


/**
 * 订单管理后台控制器
 * Created by zhong on 2016/11/6 0006.
 */
@Controller
@RequestMapping("order")
public class OrderAdminController extends BaseController {

    @Autowired
    OrdersDao ordersDao;
    @Autowired
    PriceDao priceDao;
    @Autowired
    DicDao dicDao;

    
    private static final String path = "page/order";
    /**
     * 展示訂單列表
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String list(Model model,Dic dic,Orders orders) {
        if (orders==null){
            model.addAttribute("orders",ordersDao.getAll());
        }else{
            model.addAttribute("orders",ordersDao.findByParam(orders));
        }
        dic.setDicNo(1000);
        model.addAttribute("order",orders);
        model.addAttribute("statusList",dicDao.findByParam(dic));
        return path+"/list";
    }

    @RequestMapping("/create")
    public String create(Model model) {
        Orders order = new Orders();
        List<Price> priceList = priceDao.getAll();
        for (Price price : priceList) {
            order.setPrice(price.getCost());
            break;
        }
        model.addAttribute("order",order);
        model.addAttribute("prices",priceList);
        return path+"/edit";
    }

    @RequestMapping("/edit")
    public String edit(Long id, Model model){
        model.addAttribute("order", ordersDao.getById(id));
        model.addAttribute("prices",priceDao.getAll());
        return path+"/edit";
    }

    @RequestMapping(value = "/confirm",method = RequestMethod.GET)
    public String confirm(Long id, Model model){
        model.addAttribute("order", ordersDao.getById(id));
        model.addAttribute("prices",priceDao.getAll());
        return path+"/confirm";
    }

    @RequestMapping(value = "/confirm",method = RequestMethod.POST)
    public String confirm(@ModelAttribute Orders orders, RedirectAttributes redirectAttributes) {
        if (orders.getDeliveryDate()!=null){
            orders.setStatus(3);
            ordersDao.updateStatus(orders);
            redirectAttributes.addFlashAttribute("message", "订单【" + orders.getId() + "】操作成功");
            return "redirect:/order/list";
        }else {
            return "redirect:/order/confirm?id="+orders.getId().toString();
        }

    }

    @RequestMapping(value = "/delivery",method = RequestMethod.GET)
    public String deliver(Long id, Model model){
        model.addAttribute("order", ordersDao.getById(id));
        model.addAttribute("prices",priceDao.getAll());
        return path+"/delivery";
    }

    @RequestMapping(value = "/delivery",method = RequestMethod.POST)
    public String deliver(@ModelAttribute Orders orders, RedirectAttributes redirectAttributes) {
        if (orders.getDeliveryDate()!=null){
            orders.setStatus(4);
            ordersDao.updateStatus(orders);
            redirectAttributes.addFlashAttribute("message", "订单【" + orders.getId() + "】操作成功");
            return "redirect:/order/list";
        }else {
            return "redirect:/order/delivery?id="+orders.getId().toString();
        }
    }

    @RequestMapping(value = "/finish",method = RequestMethod.GET)
    public String finish(Long id, Model model){
        model.addAttribute("order", ordersDao.getById(id));
        model.addAttribute("prices",priceDao.getAll());
        return path+"/finish";
    }

    @RequestMapping(value = "/finish",method = RequestMethod.POST)
    public String finish(@ModelAttribute Orders orders, RedirectAttributes redirectAttributes) {
        if (orders.getDeliveryDate()!=null){
            orders.setStatus(5);
            ordersDao.updateStatus(orders);
            redirectAttributes.addFlashAttribute("message", "订单【" + orders.getId() + "】操作成功");
            return "redirect:/order/list";
        }else {
            return "redirect:/order/finish?id="+orders.getId().toString();
        }
    }

    @RequestMapping(value = "/export",method = RequestMethod.GET)
    public void finish(Model model,HttpServletResponse response,Orders orders){
        List<Orders> ordersList = ordersDao.findByParam(orders);
        LinkedHashMap<String, String> propertyHeaderMap = new LinkedHashMap<>();
        propertyHeaderMap.put("id", "订单号");
        propertyHeaderMap.put("email", "注册邮箱");
        propertyHeaderMap.put("name", "收货人");
        propertyHeaderMap.put("mobile", "联系方式");
        propertyHeaderMap.put("orderTime", "下单时间");
        propertyHeaderMap.put("address", "收货地址");
        propertyHeaderMap.put("leaveMessage", "留言");
        propertyHeaderMap.put("qty", "数量");
        propertyHeaderMap.put("cost", "价格");
        propertyHeaderMap.put("price", "单价");
        propertyHeaderMap.put("statusName", "订单状态");
        //直接获取Student中的sexName，而不是sex
        propertyHeaderMap.put("deliveryDate", "发货时间");
        propertyHeaderMap.put("logistics", "快递公司");
        propertyHeaderMap.put("trackingNo", "快递单号");
        propertyHeaderMap.put("recConfirmMessage", "确认收货留言");
        try {
            //设置文件MIME类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置Content-Disposition
            response.setHeader("Content-Disposition", "attachment;filename="+ DateUtils.formatDate(new Date(),"yyyyMMddhhmmss")+".xlsx");
            //生成excel表格
            XSSFWorkbook ex = ExcelUtil.generateXlsxWorkbook("订单数据", propertyHeaderMap, ordersList);
            ex.write(response.getOutputStream());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/save")
    public String save(@ModelAttribute Orders orders, RedirectAttributes redirectAttributes) {
        if (orders!=null){
            //使用服务器上面的金额
            for (Price price : priceDao.getAll()) {
                if (price.getQty().equals(orders.getQty())){
                    orders.setCost(price.getCost());
                    orders.setPrice(price.getAvg());
                    break;
                }
            }
            if (orders.getId()==null) {
                orders.setStatus(1);
                ordersDao.insert(orders);
            } else {
                ordersDao.update(orders);
            }
            redirectAttributes.addFlashAttribute("message", "订单【" + orders.getId() + "】操作成功");
        }
        return "redirect:/order/list";
    }


    @RequestMapping("delete")
    public String delete(Long id, RedirectAttributes redirectAttributes) {
        ordersDao.delete(id);
        redirectAttributes.addFlashAttribute("message", "删除订单成功");
        return "redirect:/order/list";
    }

}
